package com.itheima.reggie.web.exception;


//使用异常处理器进行全局异常捕获

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;

//全局异常捕获
@ControllerAdvice(annotations = {RestController.class, Controller.class})//可以通过属性annotations指定拦截哪一类的
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)//来指定拦截的是那一类型的异常
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.error("ex.getMessage");
        if (ex.getMessage().contains("Duplicate entry")){
            String[] split = ex.getMessage().split(" ");
            String msg = split[2] +"已存在";
        }
        return R.error("用户名已存在");
    }
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex){
        log.error(ex.getMessage());
        return R.error(ex.getMessage());
    }
}
